package com.api.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.api.entity.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.api.entity.table.SysConfigTableDef.SYS_CONFIG;

/**
 * @Description: 描述
 * @Author: yangshfieng
 * @CreateDate: 2023/6/25
 */

@Slf4j
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Autowired
    RedisService redisService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        // 注册 Sa-Token 拦截器，定义详细认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            log.info("staken 检查校验 handler ==> {}", handler);

            // 指定一条 match 规则
            SaRouter.match("/**")    // 拦截的 path 列表，可以写多个 */
            //排除静态文件
            .notMatch("/static/**")
            .notMatch("/img/**")
            .notMatch("**/*.html", "**/*.css", "**/*.js", "**/*.png", "**/*.jpng", "**/*.jpg")
            .notMatch("/doLogin")
            .notMatch("/upload/localUpload")//图片上传测试
            .check(r -> {
                if(!StpUtil.isLogin()){
                    throw new NotLoginException("请登录后再访问","","-1");
                }
                // 系统登录时间校验
                DateTime now = DateUtil.date();// 获取当前时间
                int restrict_login_time_start = 0;
                int restrict_login_time_end = 24;

                if(!(redisService.hasKey("restrict_login_time_start") && redisService.hasKey("restrict_login_time_end"))){
                    SysConfig config = SysConfig.create().select(SYS_CONFIG.ALL_COLUMNS).where(SYS_CONFIG.CONFIG_TYPE.eq("restrict_login_time")).and(SYS_CONFIG.STATUS.eq(1)).orderBy(SysConfig::getId, false).one();
                    if(null != config && StringUtils.isNotBlank(config.getData1()) && StringUtils.isNotBlank(config.getData2())){
                        // 定义系统限制的时间
                        restrict_login_time_start = Integer.parseInt(config.getData1());
                        restrict_login_time_end = Integer.parseInt(config.getData2());
                        redisService.setCacheObject("restrict_login_time_start", restrict_login_time_start,8L, TimeUnit.HOURS);
                        redisService.setCacheObject("restrict_login_time_end", restrict_login_time_end,8L, TimeUnit.HOURS);
                    }
                }
                else{
                    restrict_login_time_start = redisService.getCacheObject("restrict_login_time_start");
                    restrict_login_time_end = redisService.getCacheObject("restrict_login_time_end");
                }
                DateTime morningStart = DateUtil.beginOfDay(now).offset(DateField.HOUR, restrict_login_time_start);
                DateTime eveningEnd = DateUtil.beginOfDay(now).offset(DateField.HOUR, restrict_login_time_end);
                // 校验当前时间是否在 限制的登录时间 之间
                boolean isWithinRange = now.isAfterOrEquals(morningStart) && now.isBeforeOrEquals(eveningEnd);
//                log.info("now ==> {}", now);
//                log.info("morningStart ==> {}", morningStart);
//                log.info("eveningEnd ==> {}", eveningEnd);
//                log.info("isWithinRange ==> {}", isWithinRange);
                if (!isWithinRange) {
                    Integer roleType = 50;
                    Object cacheObject = redisService.getCacheObject(RedisConstant.USER_INFO + StpUtil.getLoginId());
                    Map<String, Object> map = BeanUtil.beanToMap(cacheObject);
                    if(MapUtil.isNotEmpty(map) && null != map.get("roleType")){
                        roleType = Integer.parseInt(map.get("roleType").toString());
                    }
                    if(roleType.intValue() != 10 && roleType.intValue() != 20){
                        throw new NotLoginException("当前时间段，系统暂不开放","","-1");
                    }
                }

            });
        })).addPathPatterns("/**");
    }

}
